﻿using AutoMapper;
using BS.Infra;
using BS.Infra.Interface;
using MediatR;

namespace BS.Read.Api.Handler.Addresss
{
    public class GetAddressCommandHandler : IRequestHandler<ShowAddressRequestDTO, ApiResult>
    {
        private readonly IAddressRepository _addressRepository;

        private readonly IMapper _mapper;

        private readonly ILogger<GetAddressCommandHandler>   _logger;

        public GetAddressCommandHandler(IAddressRepository addressRepository, IMapper mapper, ILogger<GetAddressCommandHandler> logger)
        {
            _addressRepository = addressRepository;
            _mapper = mapper;
            _logger = logger;
        }
        public async Task<ApiResult> Handle(ShowAddressRequestDTO request, CancellationToken cancellationToken)
        {
            return await Task.FromResult(ApiResult.Ok(await GetAddressDetail()));
        }

        private async Task<IList<ShowAddressReponseDTO>> GetAddressDetail(int partId = 0)
        {
            var address = await _addressRepository.GetAllAsync(x => x.Pid == partId);

            var result = _mapper.Map<IList<ShowAddressReponseDTO>>(address);
            foreach (var item in result)
            {
                item.Children = await GetAddressDetail(item.AddressId);
            }
            return result;
        }
    }
}
public class ShowAddressRequestDTO:IRequest<ApiResult>
{

}
public class ShowAddressReponseDTO
{
    public int AddressId { get; set; }
    /// <summary>
    /// 地址名称
    /// </summary>
    public string AddressName { get; set; } = string.Empty;

    /// <summary>
    /// Children
    /// </summary>
    public IList<ShowAddressReponseDTO> Children { get; set; } = new List<ShowAddressReponseDTO>();
}